package com.minelx.datamicroscope.core.query.literalcondition;

import com.minelx.datamicroscope.core.condition.RawCondition;
import com.minelx.datamicroscope.core.query.AliasedKey;
import com.minelx.datamicroscope.core.query.Resource;
import com.minelx.hellopandas.core.DataFrameDescription;
import io.gitee.minelx.filesystem.File;
import io.gitee.minelx.filesystem.TempPath;
import io.gitee.minelx.filesystem.init.OpenPolicy;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

class ContentAndFieldLiteralCondition implements LiteralCondition {
    private final String content;

    private final List<AliasedKey> field;

    ContentAndFieldLiteralCondition(String content, List<AliasedKey> field) {
        this.content = content;
        this.field = field;
    }

    @Override
    public RawCondition toRawCondition(TempPath tempDir) {
        File tempFile = saveContentAsFile(tempDir, content);

        return RawCondition.in_or_and__with_inputStream_support(
                field,
                tempFile::inputStream,
                DataFrameDescription.create(
                        tempFile.path().uri(),
                        Resource.dtypesFromAliasedKeys(field)));
    }

    private File saveContentAsFile(TempPath tempDirectory, String content) {
        try {
            File tempFile = tempDirectory.dir()
                    .child().file(UUID.randomUUID().toString(), OpenPolicy.CREATE);
            tempFile.write(content, StandardCharsets.UTF_8);
            return tempFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
